﻿using System.IO;
using UnityEditor;
using UnityEngine;

public class CreateJson : ICreateWindow
{
    Transform transform;
    private string jsonStr;

    string tempStr = "{\"ID\":{0},\"name\":\"{1}\",\"px\":{2},\"py\":{3},\"pz\":{4}," +
        "\"rx\":{5},\"ry\":{6},\"rz\":{7},\"rw\":{8},\"sx\":{9},\"sy\":{10},\"sz\":{11}}";

    public void CreateWindow(GameObject go, bool script)
    {
        transform = go.transform;
        string path = Application.dataPath + "/Resources/Json";
        path = EditorUtility.SaveFilePanel("Create Json", path, "newJson", "json");
        if (string.IsNullOrEmpty(path)) { return; }

        using (var file = File.CreateText(path))
        {
            file.WriteLine(MakeToJson());
        }

        AssetDatabase.Refresh();
        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
    }
    
    string MakeToJson()
    {
        jsonStr = "[\n"; int i = 1;
        foreach (Transform child in transform)
        {
            string[] args = child.name.Split('_');
            if (args.Length < 2) { continue; }

            string temp = string.Format(tempStr, args[1], args[0], child.position.x, child.position.y, child.position.z, child.rotation.x,
                child.rotation.y, child.rotation.z, child.rotation.w, child.localScale.x, child.localScale.y, child.localScale.z);

            if (i < transform.childCount)
            {
                temp += ",\n";
            }
            jsonStr += temp; i++;
        }
        jsonStr += "\n]";
        return jsonStr;
    }
}